package com.aiju.cash.ui.main;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.bean.Message;
import com.aiju.cash.R;
import com.aiju.cash.core.api.DataJson;
import com.aiju.cash.core.api.MessageApi;
import com.aiju.utils.DateUtil;
import com.aiju.utils.L;
import com.aiju.utils.T;
import com.aiju.utils.Util;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chanven.lib.cptr.loadmore.SwipeRefreshHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * @author: 佐为
 * @date: 2017-01-03 17:02
 * @version: V1.0
 * @Description: 消息
 */
public class MessageActivity extends BaseTitleActivity implements SwipeRefreshHelper.OnSwipeRefreshListener, OnLoadMoreListener {

    private SwipeRefreshLayout mSryt;
    private ListView mListView;

    private View view;
    private ListViewAdapter mAdapter;
    private SwipeRefreshHelper mSwipeRefreshHelper;

    private int page = 1;
    private int pageSize = 10;
    private List<Message> messages = new ArrayList<>();
    private boolean isLoad;
    private boolean isRefresh;

    private MessageApi messageApi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);
        setCenterTitle("消息通知");
        initView();
        if (mUser.isAdmin()) {
            L.d("店长消息");
            requestMessage();
        } else {
            L.d("店员消息");
            requestMessage1();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView() {
        messageApi = new MessageApi();
        view = findViewById(R.id.iv_empty);
        mSryt = (SwipeRefreshLayout) this.findViewById(R.id.sryt_swipe_listview);
        mListView = (ListView) findViewById(R.id.lv_swipe_listview);
        mSryt.setColorSchemeColors(getResources().getColor(R.color.app_title_color));
        mAdapter = new ListViewAdapter(MessageActivity.this, messages);
        mListView.setAdapter(mAdapter);
        mSwipeRefreshHelper = new SwipeRefreshHelper(mSryt);
        mSwipeRefreshHelper.setOnSwipeRefreshListener(MessageActivity.this);
        mSwipeRefreshHelper.setOnLoadMoreListener(MessageActivity.this);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
       /*         Message message = messages.get(position);
                if (message.getMsgType() == "9") {//9非支付消息
                    return;
                }
                Intent intent = new Intent(MessageActivity.this, BlotterInfoActvity.class);
                intent.putExtra("id", message.getExt());
                intent.putExtra("type", 1);
                intent.putExtra("title", message.getSubject());
                startActivity(intent);*/
            }
        });
    }

    /**
     * 店长
     */
    private void requestMessage() {
        mDialogHelper.showLoadingProgressDialog();
        messageApi.listByAdmin(mUser.getShop().getStoreId(), mUser.getToken(), String.valueOf(page),
                String.valueOf(pageSize), new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        T.ToastNetError();
                        mDialogHelper.dismissProgressDialog();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        mDialogHelper.dismissProgressDialog();
                        DataJson dataJson = new DataJson(response);
                        if (dataJson.isSuccess()) {
                            final List<Message> da = new Gson().fromJson(dataJson.getData().toString(), new TypeToken<List<Message>>() {
                            }.getType());
                            if (!Util.isEmpty(da)) {
                                if (isRefresh) {
                                    messages.clear();
                                }
                                messages.addAll(da);
                            }
                            mAdapter.notifyDataSetChanged();
                            completeView(da);
                        } else {
                            T.ToastShort(dataJson.getMsg());
                        }
                    }
                });
    }

    /**
     * 店员
     */
    private void requestMessage1() {
        mDialogHelper.showLoadingProgressDialog();
        messageApi.listByClerk(mUser.getOperatorId(), mUser.getToken(), String.valueOf(page),
                String.valueOf(pageSize), new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        T.ToastNetError();
                        mDialogHelper.dismissProgressDialog();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        mDialogHelper.dismissProgressDialog();
                        DataJson dataJson = new DataJson(response);
                        if (dataJson.isSuccess()) {
                            final List<Message> da = new Gson().fromJson(dataJson.getData().toString(), new TypeToken<List<Message>>() {
                            }.getType());
                            if (!Util.isEmpty(da)) {
                                if (isRefresh) {
                                    messages.clear();
                                }
                                messages.addAll(da);
                            }
                            mAdapter.notifyDataSetChanged();
                            completeView(da);
                        } else {
                            T.ToastShort(dataJson.getMsg());
                        }
                    }
                });
    }

    @Override
    public void loadMore() {
        isLoad = true;
        page += 1;
        if (mUser.isAdmin()) {
            requestMessage();
        } else {
            requestMessage1();
        }
    }

    @Override
    public void onfresh() {
        isRefresh = true;
        page = 1;
        if (mUser.isAdmin()) {
            requestMessage();
        } else {
            requestMessage1();
        }
    }

    /**
     * 加载完成视图动作
     *
     * @param blotterLists
     */
    private void completeView(List<Message> blotterLists) {
        //加载
        if (isLoad) {
            isLoad = false;
            mSwipeRefreshHelper.loadMoreComplete(true);
        }
        //刷新
        if (isRefresh) {
            isRefresh = false;
            mSwipeRefreshHelper.refreshComplete();
            mSwipeRefreshHelper.setLoadMoreEnable(true);
        }

        if (blotterLists.size() < pageSize) {
            mSwipeRefreshHelper.setLoadMoreEnable(false);
        } else {
            mSwipeRefreshHelper.setLoadMoreEnable(true);
        }
        checkIfEmpty();
    }

    private void checkIfEmpty() {
        if (mAdapter != null && mSwipeRefreshHelper != null) {
            final boolean emptyViewVisible = mAdapter.isEmpty();
            if (emptyViewVisible) {
                view.setVisibility(View.VISIBLE);
            } else {
                view.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 适配
     */
    public class ListViewAdapter extends BaseAdapter {
        private List<Message> datas;
        private LayoutInflater inflater;

        public ListViewAdapter(Context context, List<Message> data) {
            super();
            inflater = LayoutInflater.from(context);
            datas = data;
        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int position) {
            return datas.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View inflate = inflater.inflate(R.layout.item_message, parent, false);
            Message message = messages.get(position);

            ImageView imageView = (ImageView) inflate.findViewById(R.id.iv_message_pic);
            TextView name = (TextView) inflate.findViewById(R.id.tv_message_name);
            TextView price = (TextView) inflate.findViewById(R.id.tv_message_price);
            TextView time = (TextView) inflate.findViewById(R.id.tv_message_time);
            TextView state = (TextView) inflate.findViewById(R.id.tv_message_state);

            if (message.getMsgType().equals("0")) {
                imageView.setImageResource(R.mipmap.icon_blotter_money);
            } else if (message.getMsgType().equals("1")) {
                imageView.setImageResource(R.mipmap.icon_message_zhifu);
            } else if (message.getMsgType().equals("2")) {
                imageView.setImageResource(R.mipmap.icon_message_wechat);
            } else if (message.getMsgType().equals("3")) {
                imageView.setImageResource(R.mipmap.icon_message_qr);
            } else {
                price.setVisibility(View.GONE);
                imageView.setImageResource(R.mipmap.icon_message_user);
            }

            name.setText(message.getSubject());
            price.setText(message.getMoney());
            time.setText(DateUtil.formatDateStr2Desc(message.getCreateDate(),""));
            state.setText(message.getContent());
            return inflate;
        }
    }
}
